<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        {{$t('route.order')}}
        <i v-if='false' class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <el-scrollbar class="page-content">
      <div class="content-wrapper">
        <el-card>
          <basic-table
            tableName='orderManage'
            v-loading='loading'
            ref='orderManage'
            :immediate="!this.$route.query.table_page"
            :pageMethod="(params) => {
              params.search = this.searchValue;
              if (tableSearch) {
                params.page = 1;
                tableSearch = false;
            }
              params.status = this.isOperationStatus;
              params.action = this.orderType;
              params.order_user_name = cloudTenantSearchName;
              return $orinusApi.getOrders(params)
            }"
          >
            <template #table-options="tableSlotData">
              <div class="table-left-options">
                <el-button type="primary" class="icon-button setting-button" style="width: auto;" @click="exportOrderInfo" :disabled="loading">
                  <i class="iconfont icon-exittuichu" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{$t('order.exportOrder')}}</span>
                </el-button>
                <el-button type="primary" class="icon-button setting-button" style="width: auto;" @click="batchDelete(tableSlotData.table.selectRows)" :disabled="loading || tableSlotData.table.selectRows.length <= 0">
                  <i class="iconfont iconzhongyiicon_shanchu" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{$t('common.delete')}}</span>
                </el-button>
                <el-button class="icon-button setting-button" style="width: auto;" @click="operationOrder(tableSlotData.table.selectRows, 'retry')" :disabled="loading || tableSlotData.table.selectRows.length <= 0">
                  <i class="iconfont iconzhongyiicon_zhongzhi" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{$t('order.retry')}}</span>
                </el-button>
                <el-button class="icon-button setting-button" style="width: auto;" @click="operationOrder(tableSlotData.table.selectRows, 'confirmFail')" :disabled="loading || tableSlotData.table.selectRows.length <= 0">
                  <i class="iconfont iconzhongyiicon_yunxu" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{$t('order.confirmFail')}}</span>
                </el-button>
              </div>
              <div class="table-right-options">
                <el-select default-first-option v-model="isOperationStatus" @change="tableSlotData.table.refresh(true)" :disabled="tableSlotData.table.loading" style="margin-right: 10px;">
                  <el-option
                    v-for="status in operationStatus"
                    :key="status.value"
                    :label="status.label"
                    :value="status.value">
                  </el-option>
                </el-select>
                <el-select default-first-option v-model="orderType" @change="tableSlotData.table.refresh(true)" :disabled="tableSlotData.table.loading" style="margin-right: 10px;">
                  <el-option
                    v-for="item in orderTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-input v-model="searchValue" :placeholder="$t('order.searchbyOrder')" @keyup.enter.native="tableSearchChange(tableSlotData)" style="width:200px">
                </el-input>
                <el-button @click="tableSearchChange(tableSlotData)" type="primary" style="margin-left: 10px;" >{{ $t('common.search') }}</el-button>
              </div>
            </template>
            <template #table-column="tableSlotData">
              <el-table-column type="selection" width="40" align="center"></el-table-column>
              <!-- 订单号 -->
              <el-table-column
                prop="order_id"
                :label="$t('order.orderNumber')"
                >
              </el-table-column>
              <!-- 租户 -->
              <el-table-column
                v-if="authrole === 'system_admin'"
                :label="$t('common.tenant')"
                prop='order_user_name'
                >
              </el-table-column>
              <!-- 资源池ID -->
              <el-table-column
                prop="pool_code"
                :label="$t('resource.resourcePoolCode')"
                >
              </el-table-column>
              <!-- 资源池名称 -->
              <el-table-column
                prop="pool_name_zh"
                :label="$t('resource.resourcePoolName')"
                >
                <template #default="props">
                  {{ initPoolName(props.row) }}
                </template>
              </el-table-column>
              <!-- 最后操作 -->
              <el-table-column
                :label="$t('order.lastAction')"
                prop='action'
                :formatter="
                  (row, column) => {
                    if (row.action) {
                      return $t(`order.action.${row.action}`);
                    }
                    return '';
                  }
                "
              >
              </el-table-column>
              <!-- 操作状态 -->
              <el-table-column
                prop="status"
                :label="$t('order.operatingStatus')"
                :formatter="
                  (row, column) => {
                    if (row.status) {
                      return $t(`order.status.${row.status}`);
                    }
                    return '';
                  }
                "
                >
              </el-table-column>
              <!-- 操作时间 -->
              <el-table-column
                prop="action_at"
                :label="$t('logs.operationTime')"
                >
								<template #default="props">
                  <span>{{ parseTime(new Date(props.row.action_at)) }}</span>
                </template>
              </el-table-column>
              <!-- 创建时间 -->
              <el-table-column
                prop="created_at"
                :label="$t('policy.CreationTime')"
                >
								<template #default="props">
                  <span>{{ parseTime(new Date(props.row.created_at)) }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.action')" width="150">
                <!-- 操作 -->
                <template #default="props">
                  <!-- 删除 -->
                  <link-button
                    :content="$t('common.delete')"
                    :size="10"
                    :font-size="'12px'"
                    style="margin-right: 15px"
                    @click="deleteRow(props.row)"
                  />
                  <el-dropdown>
                    <el-button type="text" class="el-dropdown-link">
                      {{ $t("common.More")
                      }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <!-- 订单资产管理 -->
                      <el-dropdown-item
                        @click.native="$router.push({
                          name: 'OrderManage',
                          query: {
                            id: props.row.id,
                            order_id: props.row.order_id,
                            status: props.row.status,
                            index_table_page: tableSlotData.table.currentPage
                          }
                        })"
                        >{{$t('order.orderAssetManagement')}}</el-dropdown-item
                      >
                      <!-- 重试订单操作 -->
                      <el-dropdown-item
                        @click.native="operationOrder(props.row, 'retry')"
                        >{{$t('order.retryOrderOperation')}}</el-dropdown-item
                      >
                      <!-- 修改订单带宽 -->
                      <el-dropdown-item
                        @click.native="editBandwidth(props.row)"
                        >{{$t('order.editOrderBandwidth')}}</el-dropdown-item
                      >
                      <!-- 确认操作失败 -->
                      <el-dropdown-item
                        @click.native="operationOrder(props.row, 'confirmFail')"
                        >{{$t('order.confirmOperationFail')}}</el-dropdown-item
                      >
                      <!-- 查看消息记录 -->
                      <el-dropdown-item
                       @click.native="$router.push({
                          name: 'OrderMassage',
                          query: {
                            order_id: props.row.order_id,
                            index_table_page: tableSlotData.table.currentPage
                          }
                        })"
                        >{{$t('order.viewMessageHistory')}}</el-dropdown-item
                      >
                      <!-- 修改订单状态 -->
                      <el-dropdown-item
                       @click.native="changeOrderStatus(props.row)">
                        {{$t('order.changeOrderStatus')}}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
						<template #others-elements="tableSlotData">
              <delete-order @success="tableSlotData.table.refresh" ref="deleteFormDialog"/>
              <operation-order @success="tableSlotData.table.refresh" ref="retryDialog"/>
              <edit-band-width @success="tableSlotData.table.refresh" ref="editBandwidth" />
              <change-order-status ref="ChangeOrderStatus" @success="tableSlotData.table.refresh"></change-order-status>
            </template>
          </basic-table>
        </el-card>
      </div>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import LinkButton from "../../components/Basic/Button/LinkButton.vue";
import BasicTable from '../../components/Basic/Table/BasicTable.vue';
import DeleteOrder from './components/deleteOrderFormdialog.vue';
import OperationOrder from './components/operationOrderConfirmDialog.vue';
import EditBandWidth from './components/editOrderBandwidthFormDialog.vue';
import { parseTime, loginTimeslotToString } from '../../utils';
import { AuthModule } from '../../store/modules/auth';
import { AppModule } from '../../store/modules/app';
import orinusApi from '../../api/orinusApi';
import { Prop } from 'vue-property-decorator';
import ChangeOrderStatus from './components/changeOrderStatus.vue';
import { parseInt } from 'lodash';
import { exportJson2Excel } from '../../utils/excel'
export default Vue.extend({
  components: {
    BasicTable,
    LinkButton,
    DeleteOrder,
    OperationOrder,
    EditBandWidth,
    ChangeOrderStatus
  },
	computed: {
    parseTime: () => parseTime,
    loginTimeslotToString: () => loginTimeslotToString
  },
  data() {
    return {
      searchValue: '',
      loading: false,
      tenant_options: [],
      language: AppModule.language,
      authrole: AuthModule.authrole,
      cloudTenantList: [{
        id:'',
        name:''
      }],
      cloudTenantSearchName: "",
      tableSearch: false,
      poolData: [],
      isOperationStatus: '',
      operationStatus: [{
        value: '',
        label: this.$t('order.allOperationStatus')
      },{
        value: 'successful',
        label: this.$t('order.successful')
      },{
        value: 'failed',
        label: this.$t('order.fail')
      },{
        value: 'doing',
        label: this.$t('order.doing')
      },{
        value: 'timeout',
        label: this.$t('order.timeout')
      }],
      orderType: "",
      orderTypeList: [{
        value: '',
        label: this.$t('order.allActiontype')
      },{
        value: 'create',
        label: this.$t('order.action.create')
      },{
        value: 'cancel',
        label: this.$t('order.action.cancel')
      },{
        value: 'unsubscribe',
        label: this.$t('order.action.unsubscribe')
      },{
        value: 'change',
        label: this.$t('order.action.change')
      },{
        value: 'freeze',
        label: this.$t('order.action.freeze')
      },{
        value: 'restore',
        label: this.$t('order.action.restore')
      },{
        value: 'transfer',
        label: this.$t('order.action.transfer')
      },{
        value: 'replace',
        label: this.$t('order.action.replace')
      },{
        value: 'bandwidth',
        label: this.$t('order.action.bandwidth')
      },{
        value: 'change_desktop',
        label: this.$t('order.action.change_desktop')
      },{
        value: 'renew',
        label: this.$t('order.action.renew')
      }]
    }
  },
  created() {
    if (AuthModule.authrole === 'system_admin') {
      let tenant_options: any = [];
      (this as any).$tunnyApi.apiGetTenantList().then((res: any) => {
        res.forEach((item: any) => {
          let obj: any = {};
          obj.value = item.id;
          obj.label = item.name
          tenant_options.push(obj);
        });
        this.tenant_options = tenant_options;
      }).catch(() => {
        console.log('tenant-userList-get-error');
      });
      (this as any).getCloudTenantList();
    }
  },
  mounted(){
    //获取资源池名称
    this.$pandaApi.apiGetResourcePool().then((res: any) => {
      for(let i in res){
        let obj = {
          pool_code: res[i].pool_code,
          pool_name: res[i].name
        }
        this.poolData.push(obj as never);
      }
    })
    if(!this.$route.params.isBack) {
      (this.$refs["orderManage"] as any).tableCurrentPageChange(1);
    }else if (this.$route.query.table_page) {
      (this.$refs["orderManage"] as any).tableCurrentPageChange(parseInt(this.$route.query.table_page as string));
    }
  },
  beforeDestroy() {
  },
  methods: {
    initPoolName(row: any) {
      for(let i=0;i<this.poolData.length;i++) {
        if(row.pool_code == (this as any).poolData[i].pool_code) {
          return (this as any).poolData[i].pool_name
        }
      }
    },
    // 页面刷新重置page
    tableSearchChange(table: any) {
      (this as any).tableSearch = true;
      table.table.refresh(true);
    },
    initTenantName(id: any) {
      for(let i in (this as any).cloudTenantList) {
        if (id === (this as any).cloudTenantList[i].id) {
          return (this as any).cloudTenantList[i].name
        }
      }
      return ;
    },
    getCloudTenantList() {
      (this as any).cloudTenantLoading = true;
      (this as any).$tunnyApi.apiGetTenantList({}).then((res: any) => {
        res = res.sort((a: any, b: any) => (a.name).localeCompare((b.name), 'zh-Hans-CN', { sensitivity: 'accent' }));
        (this as any).cloudTenantList = res;
        (this as any).cloudTenantLoading = false;
      });
    },
    batchDelete(selectRows: Array<any>) {
      (this as any).$refs.deleteFormDialog.init({
        title: (this as any).$t('order.deleteOrderTitle').toString(),
        tip: (this as any).$t('order.batchdeleteOrderContent').toString(),
        message: (this as any).$t('order.deleteOrderHelp').toString(),
        orderList: selectRows
      });
    },
    deleteRow(row: any) {
      (this as any).$refs.deleteFormDialog.init({
        title: (this as any).$t('order.deleteOrderTitle').toString(),
        tip: (this as any).$t('order.deleteOrderContent').toString(),
        message: (this as any).$t('order.deleteOrderHelp').toString(),
        orderList: [row]
      });
    },
    getTenantName(id: any) {
      let label = "";
      this.tenant_options.forEach((item: any) => {
        if (item.value == id) {
           label = item.label;
        }
      })
      return label;
    },
    operationOrder(data: any, type: string) {
      let obj: any = {};
      obj.data = data;
      obj.type = type;
      (this.$refs["retryDialog"] as any).init(obj);
    },
    editBandwidth(data: any) {
      let obj:any = {};
      obj.data = data;
      (this.$refs["editBandwidth"] as any).init(obj);
    },
    changeOrderStatus(data: any) {
      (this as any).$refs['ChangeOrderStatus'].init(data);
    },
    // 格式化json
    formatJson(filterVal: any, jsonData: any) {
      return jsonData.map((v: any) => filterVal.map((j: any) => v[j]));
    },

    // list整合
    listData(list: any) {
      console.log(list, 'list');
      const data: any[] = [];
      list.map((item: any) => {
        const obj: any = {};
        obj.orderId = item.order_id;
        obj.tenantName = item.order_user_name;
        obj.resourceID = item.pool_code;
        obj.resourceName = (this as any).initPoolName(item);
        obj.endAction = (this as any).$t(`order.action.${item.action}`);
        obj.status = (this as any).$t(`order.status.${item.status}`);
        obj.action_time = parseTime(new Date(item.action_at));
        obj.create_at = parseTime(new Date(item.created_at));
        data.push(obj);
      });
      return data;
    },
    // 导出订单信息
    exportOrderInfo(list: any) {
      let params: any = {};
      params.status = this.isOperationStatus;
      params.action = this.orderType;
      params.search = this.searchValue;
      (this as any).$orinusApi.getOrders(params).then((res: any) => {
        console.log(res);
        if (res && res.length > 0) {
            require.ensure([], () => {
            let tHeader: string[] = [];
            let excelName = "";
            let filterVal: any = [];
            excelName = "订单信息";
            tHeader = ["订单号", "租户", "资源池ID", "资源池名称", "最后操作", "操作状态", "操作时间", "创建时间"];
            filterVal = ["orderId", "tenantName", "resourceID", "resourceName", "endAction", "status", "action_time", 'create_at'];
            const data = this.formatJson(filterVal, this.listData(res));
            exportJson2Excel(tHeader, data, excelName);
          });
        }
      })
  }
  }
})
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #EFF1F4;

  .page-header {
    height: 60px;
    background-color: #FFFFFF;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #D9D9D9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;
    }
  }
}

.table-left-options {
  display: flex;
}

.table-right-options {
  display: flex;

  .setting-button {
    margin-right: 10px;
  }
}

.delete-warning-icon {
  color: #FF931D;
  font-size: 20px;
  margin-right: 10px;

  &::before {
    font-size: 20px;
  }
}
</style>
